package gu.sql2java.observer;

import static com.google.common.base.Preconditions.checkNotNull;
import static gu.sql2java.observer.JDBCUtility.createConnection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

public class SimpleRowMetaDatas {

	/**
	 * 创建指定表的表元数据实例
	 * @param tablename 表名
	 * @param targetTypes 定义表的指定字段的类型,为{@code null}使用默认值
	 * @param connection  表的数据库连接
	 * @return SimpleRowMetaData 实例
	 * @throws SQLException
	 */
	public static SimpleRowMetaData create(String tablename, Map<String, Class<?>> targetTypes, Connection connection) throws SQLException{
		return new SimpleRowMetaData(checkNotNull(connection,"connection is null").getMetaData(), tablename, targetTypes);
	}

	/**
	 * 创建指定表的表元数据实例
	 * @param tablename 表名
	 * @param targetTypes 定义表的指定字段的类型,为{@code null}使用默认值
	 * @param url  JDBC URL
	 * @param user user name for connection
	 * @param password password for connection
	 * @return SimpleRowMetaData 实例
	 * @throws SQLException
	 */
	public static SimpleRowMetaData create(String tablename, Map<String, Class<?>> targetTypes, String url, String user, String password) throws SQLException{
		Connection connection = createConnection(url, user, password, null);
		try {
			return new SimpleRowMetaData(connection.getMetaData(), tablename, targetTypes);
		} finally {
			connection.close();
		}
	}

}
